#include "widget.h"
#include "ui_widget.h"
#include<QScrollBar>
#include<QTimer>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    LineMessageData date;
    layout=new QVBoxLayout(this);
    for(int i=0;i<10;i++)
    {   LineMessage*ms;
        if(i%2==0)
        {
            date.message="he\nll\now";
            date.headimage="://head/6.bmp";
            date.name="moli";
           ms=new LineMessage(date);
        }
        else
        {
            date.message="nice";
            date.headimage="://head/7.bmp";
            date.name="jack";
            ms=new LineMessage(date,MessageUser_Friend);
        }

        layout->addWidget(ms);

        ui->scrollArea->widget()->setLayout(layout);
    }



}

Widget::~Widget()
{
    delete ui;
}


// 修改后的完整代码
void Widget::on_sendmsg_clicked()
{
    QString message = ui->sendtext->toPlainText().trimmed();
    if(message.isEmpty()) {
        return;
    }

    LineMessageData date;
    date.message = message;
    date.headimage = "://head/6.bmp";
    date.name = "moli";

    LineMessage* ms = new LineMessage(date);
    layout->addWidget(ms);

    ui->sendtext->clear();

    // 强制更新UI
    ui->scrollArea->widget()->updateGeometry();
    ui->scrollArea->widget()->adjustSize();

    // 滚动到底部
    scrollToBottom();
}

void Widget::scrollToBottom()
{
    // 方法1：直接尝试
    // QScrollBar *verticalBar = ui->scrollArea->verticalScrollBar();
    // verticalBar->setValue(verticalBar->maximum());

    // 方法2：延迟确保完全滚动
    QTimer::singleShot(100, this, [this]() {
        QScrollBar *verticalBar = ui->scrollArea->verticalScrollBar();
        int max = verticalBar->maximum();
        verticalBar->setValue(max);

        //如果仍然没有滚动到底部，再次尝试
        if (verticalBar->value() != max) {
            QTimer::singleShot(50, this, [this, max]() {
                ui->scrollArea->verticalScrollBar()->setValue(max);
            });
        }
    });
}

